package com.stylefeng.sso.plugin.interceptor;

import com.stylefeng.sso.plugin.constants.SsoConstants;
import com.stylefeng.sso.plugin.properties.SsoProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * sso客户端登录拦截器
 *
 * @author fengshuonan
 * @date 2018-02-03 20:35
 */
public class SsoServerInterceptor implements HandlerInterceptor {
    private Logger log = LoggerFactory.getLogger(this.getClass());


    SsoProperties ssoProperties;

    public SsoServerInterceptor(SsoProperties ssoProperties) {
        this.ssoProperties = ssoProperties;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle SsoServer");
        HttpSession session = request.getSession();
        log.info("打印一下过滤器session的地址\t"+request.getSession());
        //获取当前用户登录标记
        Object sessionAttribute = session.getAttribute(SsoConstants.SESSION_LOGIN_FLAG);



        //如果没登录,跳转到登录页面
        if (sessionAttribute == null) {
            log.info("server未登录");
            request.setAttribute(SsoConstants.REDIRECT_PARAM_NAME, request.getParameter(SsoConstants.REDIRECT_PARAM_NAME));
            request.getRequestDispatcher("/login").forward(request, response);
            return false;
        } else {

            log.info("server已经登录\t"+sessionAttribute.toString());
            //当前用户已经登录,通过拦截器
            String requestURI = request.getRequestURI();


            String redirectUrl = request.getParameter(SsoConstants.REDIRECT_PARAM_NAME);
            //此处是获取以 REDIRECT_PARAM_NAME 为键的参数

            if (requestURI.contains("logout")){
                response.sendRedirect(redirectUrl);
                log.info("打印退出类型的地址\t"+redirectUrl);
                return true;
            }


            response.sendRedirect(redirectUrl + "?" + SsoConstants.TOKEN_PARAM_NAME + "=" + sessionAttribute.toString());
            log.info("打印了登陆成功后跳转的地址");
            log.info(redirectUrl + "?" + SsoConstants.TOKEN_PARAM_NAME + "=" + sessionAttribute.toString());

            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
